﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DotaHelp.Models;
using DotaHelp.Helpers;
using System.ServiceModel.Syndication;
using MvcReCaptcha;

namespace DotaHelp.Controllers
{

    
    public class CommandsController : Controller
    {
        DotaModel model = new DotaModel();

        protected override void Dispose(bool disposing)
        {
            base.Dispose(disposing);
            model.Dispose();
            
        }
        
        public ActionResult List(int? page, string orderBy)
        {
            var commands = model.Commands.Include("CommandsHeroes").Include("CommandsHeroes.Hero").Where(c => !c.IsDeleted);
            return View(commands.ByPage(page, orderBy, p => p.Raiting, p => p.Date, ViewData, HttpContext).ToArray());
           
        }

		[ChildActionOnly]
		public ActionResult One(Command command, bool showComments = false)
		{
			ViewData["ShowCaption"] = true;
			ViewData["ShowComments"] = showComments;
			return PartialView(command);
		}

      
        public ActionResult ListForHero(int heroId)
        {
            var commands = from c in model.Commands.Include("CommandsHeroes").Include("CommandsHeroes.Hero")
                           where c.IsDeleted == false && c.CommandsHeroes.Any(h => h.HeroId == heroId)
                           orderby c.Raiting descending, c.Date ascending
                           select c;

            return Request.IsAjaxRequest() ? (ActionResult)PartialView(commands.ToArray()) : View(commands.ToArray());
        }

        public ActionResult Add()
        {
            ViewBag.Author = Request.GetUserName();
            ViewBag.Heroes = model.Heroes.ToArray();
            return View();
        }

        [HttpPost]
		[CaptchaValidator]
        public ActionResult Add(string author, string comment, string password, string selected)
        {
            Response.SaveUserName(author);

            var c = new Command()
            {
                IpAddress = Request.ServerVariables["REMOTE_ADDR"],
                Date = DateTime.UtcNow.NowByAstana(),
                Raiting = 0,
                Author = ControllerContext.HttpContext.PrepareUserName(author),
                Comment = comment,
                Password = password
            };
                        
            foreach (var hero in selected.Split(',')
                .Select(item=>item.Split('|'))
                .Select(item=>new {pos = item[0], heroId = int.Parse(item[1])}))
            {
                c.CommandsHeroes.Add(new CommandsHero() {  HeroId = hero.heroId, Position = hero.pos });
            }

            model.Commands.AddObject(c);
            model.SaveChanges();            

            return Content(Url.Action("List"));
        }

        [Sitemap(typeof(Command), "Date")]
        public ActionResult Details(int id)
        {
            return View(model.Commands.Include("CommandsHeroes").Include("CommandsHeroes.Hero").First(c => c.Id == id));
        }

        [ChildActionOnly]
        public string Rating(int id, bool isPlus)
        {
            var command = model.Commands.First(c => c.Id == id);
            command.Raiting += isPlus ? 1 : -1;
            model.SaveChanges();
            return command.Raiting.ToString();
        }

        [Authorize(Roles = "Admin")]
        public void Delete(int id)
        {
            var c = model.Commands.First(i => i.Id == id);
            c.IsDeleted = true;
            model.SaveChanges();
        }

        [ChildActionOnly]
        [Rss]
        public IEnumerable<SyndicationItem> Rss()
        {
            var url = new UrlHelper(Request.RequestContext);

            foreach (var c in model.Commands.OrderByDescending(_ => _.Date).Take(50))
            {
                yield return new SyndicationItem("Команда", c.Comment, new Uri(url.GetBaseUrl(), url.Action("Details", "Commands", new { id = c.Id })), "c" + c.Id, c.Date);
            }
        }        
    }
}
